<template>
  <div class="flex flex-column h-100">
    <div class="flex flex-wrap justify-end">
      <!-- 区域选择 -->
      <region-cascader
        style="width: 230px"
        class="mb-10"
        :limit="2"
        :multiple="true"
        @change="regionChange"
      />
      <el-select
        v-model="queryData.alarmType"
        clearable
        filterable
        style="width: 200px"
        class="ml-10 mb-10"
        size="mini"
        :placeholder="$t('ALARM_TYPE')"
      >
        <el-option
          v-for="(item, index) in alarmTypeList"
          :key="index"
          :value="item"
          :label="$t('ALARM_TYPE_' + item)"
        />
      </el-select>
      <el-select
        v-model="queryData.alarmLevel"
        clearable
        style="width: 150px"
        class="ml-10 mb-10"
        size="mini"
        :placeholder="$t('ALARM_LEVEL')"
      >
        <el-option
          v-for="(item, index) in dictList.ALARM_LEVEL"
          :key="index"
          :value="item.value"
          :label="item.label"
        />
      </el-select>
      <el-select
        v-model="queryData.alarmStatus"
        clearable
        style="width: 150px"
        class="ml-10 mb-10"
        size="mini"
        :placeholder="$t('ALARM_STATUS')"
      >
        <el-option
          v-for="(item, index) in alarmStatusList"
          :key="index"
          :value="item.value"
          :label="item.label"
        />
      </el-select>
      <!-- 录入时间 -->
      <el-date-picker
        v-model="queryData.dateTime"
        style="width: 320px"
        class="ml-10 mb-10"
        size="mini"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        range-separator="-"
        :start-placeholder="$t('START_TIME')"
        :end-placeholder="$t('END_TIME')"
        :picker-options="pickerOptions"
        align="right"
      />
      <el-input
        v-model.trim="queryData.keyword"
        class="ml-10 mb-10"
        style="width: 200px"
        maxlength="32"
        clearable
        size="mini"
        :placeholder="$t('DEVICE_CODE') + '/' + $t('DEVICE_NAME') + '/' + $t('CONFIRMER')"
        @keyup.enter.native="$debounce(search)"
      />
      <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
        $t('QUERY')
      }}</el-button>
    </div>

    <!--告警列表-->
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="180"
      :cell-class="cellClassLevel"
      @operate="operate"
      @pageChange="pageChange"
    />

    <!-- 查看告警 -->
    <AlarmDetail
      :visible="alarmDetailVisible"
      :table-selected="tableSelected"
      @close="alarmDetailVisible = false"
    />

    <!-- 确认/取消告警 -->
    <Confirmdesc
      ref="Confirmdesc"
      :visible="dialogVisible"
      @close="dialogVisible = false"
      @loadData="loadData"
    />

    <!-- 监控信息详情 -->
    <MonitorDetail
      v-if="monitorVisible"
      :dialog-visible.sync="monitorVisible"
      :params="tableSelected"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import AlarmRecordApi from '@/api/basebiz/AlarmRecordApi'
  import LogicSegmentApi from '@/api/oen/LogicSegmentApi'
  import { getParentsById, pickerOptionsClassMonth, handleAfsMaintText } from '@/utils/common'
  import AlarmDetail from './components/AlarmDetail'
  import Confirmdesc from './components/Confirmdialog'
  import RegionCascader from '@/components/RegionCascader'
  import MonitorDetail from './components/MonitorDetail'
  import TableView from '@/components/TableView'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    name: 'InfoAlarmPage',
    components: {
      AlarmDetail,
      Confirmdesc,
      RegionCascader,
      TableView,
      MonitorDetail
    },
    data() {
      const _this = this
      return {
        queryData: {
          alarmLevel: '',
          keyword: '',
          alarmStatus: '',
          dateTime: '',
          regionIds: '',
          confirmer: '',
          alarmType: '',
          isAlarm: true
        },
        dialogVisible: false,
        tableData: [],
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        pickerOptions: pickerOptionsClassMonth(this),
        alarmDetailVisible: false,
        tableSelected: {},
        alarmStatus: '', // 修改告警状态
        currAlarm: null, // 当前选择告警
        monitorVisible: false,
        tableHeader: [
          {
            label: 'BELONGS_REGION_STATION_NAME',
            prop: 'regionTextNames',
            width: '160',
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'BELONGS_ROOM_NAME',
            prop: 'roomName',
            width: 200,
            configType: 'extend'
          },
          {
            label: 'ALARM_SOURCE_NAME',
            prop: 'deviceName',
            width: '200',
            fixed: 'left',
            configType: 'default',
            formatter(row) {
              return row.logicSegmentId ? _this.getSourceName(row.logicSegmentId) : row.deviceName
            }
          },
          {
            label: 'DEVICE_CODE',
            prop: 'deviceId',
            width: '200',
            configType: 'extend'
          },
          {
            label: 'ALARM_LEVEL',
            prop: 'alarmLevelText',
            width: '160',
            align: 'center',
            configType: 'default'
          },
          {
            label: 'ALARM_STATUS',
            prop: 'alarmStatusText',
            width: '160'
          },
          {
            label: 'ALARM_TYPE',
            prop: 'alarmTypeText',
            width: '200',
            configType: 'default'
          },
          {
            label: 'ALARM_DESCRIPTION',
            prop: 'description',
            width: '300'
          },
          {
            label: 'START_TIME',
            prop: 'startTime',
            width: '200'
          },
          {
            label: 'CONFIRM_REASON',
            prop: 'confirmDesc',
            width: '250'
          },
          {
            label: 'CONFIRM_TIME',
            prop: 'confirmTime',
            width: '200'
          },
          {
            label: 'CONFIRMER',
            prop: 'confirmer',
            width: '150'
          }
        ],
        intervalTimer: null,
        alarmTypeList: [],
        logicSegmentData: []
      }
    },
    computed: {
      ...mapGetters(['dictList', 'stationTree', 'dictMap', 'baseRegionList']),
      alarmStatusList() {
        //  告警状态
        return this.dictList.ALARM_STATUS.filter(
          item => item.value === 'READY' || item.value === 'CONFIRM'
        )
      },
      permission() {
        return this.$store.getters.getAuthData('info:alarm')
      }
    },
    created() {
      this.loadData()
    },
    activated() {
      this.loadData()
    },
    deactivated() {
      this.intervalTimer && clearTimeout(this.intervalTimer)
      this.intervalTimer = null
    },
    beforeDestroy() {
      this.intervalTimer && clearTimeout(this.intervalTimer)
      this.intervalTimer = null
    },
    methods: {
      cellClassLevel({ row, column, rowIndex, columnIndex }) {
        if (column.property === 'alarmLevelText') {
          return `alarmLevelTextLabel lev${row.alarmLevel}`
        }
      },
      search() {
        this.pageData.page = 1
        searchData = {
          ...this.queryData
        }
        if (this.queryData.alarmLevel) {
          searchData.alarmLevel = this.queryData.alarmLevel
        }
        if (this.queryData.regionIds) searchData.regionIds = this.queryData.regionIds
        if (this.queryData.keyword) searchData.keyword = this.queryData.keyword
        if (this.queryData.alarmType) searchData.alarmType = this.queryData.alarmType
        if (this.queryData.alarmStatus) {
          searchData.alarmStatus = this.queryData.alarmStatus
        }
        if (this.queryData.dateTime) {
          searchData.startTime = this.queryData.dateTime[0]
          searchData.endTime = this.queryData.dateTime[1]
        }
        this.loadData()
      },
      getAlarmType() {
        AlarmRecordApi.recordAlarmTypes({ isActive: true }).then(res => {
          this.alarmTypeList = res || []
          if (this.queryData.alarmType && !res.includes(this.queryData.alarmType)) {
            this.queryData.alarmType = ''
          }
        })
      },
      async loadData() {
        this.getAlarmType()
        // 获取列表
        const data = {
          isAlarm: true,
          ...this.pageData,
          ...searchData
        }
        delete data.total
        const res = await AlarmRecordApi.alarmRecordPage(data)
        if (!res) return
        const { list, total } = res
        const logicSegmentIds = []
        list.forEach(i => {
          if (i.regionId) {
            const trees = (getParentsById(this.stationTree, i.regionId, 'key') || []).reverse()
            if (trees.length > 0) {
              i.stationTextName = trees[trees.length - 1]['regionName'] // 站点名称
              i.regionTextNames = trees
                .map(i => i.regionName)
                .join('/') // 区域名称
              i.stationStatusText =
                this.dictMap['REGION_STATUS'][trees[trees.length - 1]['status']] // 站点状态
            } else {
              i.stationStatusText = ''
            }
          }
          i.roomName = this.getRoomName(i.roomId)
          i.logicSegmentId && logicSegmentIds.push(i.logicSegmentId)
          i.description = handleAfsMaintText(i.description) // 设备检修告警特殊处理
          i.trigger = this.$utils.handleServiceI18n(i.trigger)
          i.description = this.$utils.handleServiceI18n(i.description)
          i.deviceName = (i.device && i.device.deviceName) || ''
          i.alarmLevelText = this.dictMap['ALARM_LEVEL'][i['alarmLevel']] // 告警等级
          i.alarmTypeText = this.dictMap['ALARM_TYPE'][i['alarmType']] // 告警类型
          i.alarmStatusText = this.dictMap['ALARM_STATUS'][i['alarmStatus']] // 告警状态
          i.btns = this.getBtns(i)
        })
        if (logicSegmentIds.length) {
          const result = await LogicSegmentApi.getListBySegmentIds(logicSegmentIds)
          this.logicSegmentData = result || []
        }
        this.tableData = list
        this.pageData.total = total
        this.intervalTimer && clearTimeout(this.intervalTimer)
        this.intervalTimer = null
        this.intervalTimer = setTimeout(() => {
          this.loadData()
        }, 30 * 1000)
      },
      // 机房
      getRoomName(roomId) {
        if (!roomId) return ''
        const stationData = this.baseRegionList.find(i => i.regionId === roomId)
        return stationData ? stationData.regionName : ''
      },
      getSourceName(logicSegmentId) {
        const data = this.logicSegmentData.find(i => i.segmentId === logicSegmentId)
        return data ? data.segmentName : ''
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'monitor',
            show: row.alarmType === 'ILLEGAL_ENTRY' || row.alarmType === 'SOLAR_ENERGY_STOLEN',
            label: 'MONITOR'
          },
          {
            key: 'confirm',
            show:
              this.permission.confirm &&
              row.alarmStatus !== 'CONFIRM' &&
              row.alarmStatus !== 'CANCEL' &&
              row.alarmStatus !== 'RESTORE',
            label: 'CONFIRM'
          },
          {
            key: 'cancel',
            show: this.permission.cancel && row.isAlarm,
            label: 'CANCEL'
          }
        ]
        return btns.filter(i => i.show)
      },
      operate(data) {
        switch (data.type) {
        case 'view':
          this.tableSelected = data.data
          this.alarmDetailVisible = true
          break
        case 'monitor':
          this.tableSelected = data.data
          this.monitorVisible = true
          break
        case 'confirm':
          this.dialogVisible = true
          this.currAlarm = data.data
          this.$refs.Confirmdesc.comfirmAlarm(data.data, 'CONFIRM')
          break
        case 'cancel':
          this.dialogVisible = true
          this.currAlarm = data.data
          this.$refs.Confirmdesc.comfirmAlarm(data.data, 'CANCEL')
          break
        }
      },
      regionChange(data) {
        // 区域搜索条件改变
        // console.log(data)
        this.queryData.regionIds = data
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      }
    }
  }
</script>

